package cn.doctorpda.conference.ui.recommend;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.doctorpda.conference.MyApplication;
import cn.doctorpda.conference.R;
import cn.doctorpda.conference.adapter.InfoAdapter;
import cn.doctorpda.conference.adapter.RecommendAdapter;
import cn.doctorpda.conference.adapter.RecommendReportAdapter;
import cn.doctorpda.conference.bean.DataInfo;
import cn.doctorpda.conference.bean.DataReportInfo;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.bean.RecomHotInfo;
import cn.doctorpda.conference.bean.ReportInfoItem;
import cn.doctorpda.conference.bean.User;
import cn.doctorpda.conference.bean.doc.DataDocInfo;
import cn.doctorpda.conference.bean.doc.DocInfoItem;
import cn.doctorpda.conference.bean.meeting.AdBean;
import cn.doctorpda.conference.bean.meeting.AdInfo;
import cn.doctorpda.conference.event.GetMessage;
import cn.doctorpda.conference.event.MainEvent;
import cn.doctorpda.conference.presenter.AdPresenter;
import cn.doctorpda.conference.presenter.DocPresenter;
import cn.doctorpda.conference.presenter.RecommendPresenter;
import cn.doctorpda.conference.presenter.ReportPresenter;
import cn.doctorpda.conference.ui.BaseFragment;
import cn.doctorpda.conference.ui.checked.CheckFragment;
import cn.doctorpda.conference.ui.common.DetailActivity;
import cn.doctorpda.conference.ui.search.SearchActivity;
import cn.doctorpda.conference.utils.ImageUtils;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.utils.ScreenUtils;
import cn.doctorpda.conference.utils.T;
import cn.doctorpda.conference.view.DividerItemDecoration;
import cn.doctorpda.conference.view.FullyGridLayoutManager;
import cn.doctorpda.conference.view.bannerview.BannerView;
import cn.doctorpda.conference.view.bannerview.Kanner;
import cn.doctorpda.conference.view.callbackview.IAdView;
import cn.doctorpda.conference.view.callbackview.IBaseView;
import cn.doctorpda.conference.view.callbackview.IDocPageView;
import cn.doctorpda.conference.view.callbackview.IRecommendView;
import cn.doctorpda.conference.view.callbackview.IReportPageView;
import cn.doctorpda.conference.view.cyclescrollview.CycleScrollAdapter;
import cn.doctorpda.conference.view.cyclescrollview.CycleScrollAdapterT;
import cn.doctorpda.conference.view.cyclescrollview.CycleScrollView;
import cn.doctorpda.conference.view.cyclescrollview.CycleScrollViewT;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/16.
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class RecommendFragment extends BaseFragment implements View.OnClickListener, IRecommendView, IReportPageView, IDocPageView, SwipeRefreshLayout.OnRefreshListener, RecommendAdapter.OnItemClickListener, RecommendReportAdapter.OnItemClickListener, IAdView {

    //    private BannerView mViewPager;
    private RecyclerView mRecyclerItem1, mRecyclerItem2, mRecyclerItem3, mRecyclerItem4, mRecyclerItem5;
    private String[] urlList = {"http://pic32.nipic.com/20130829/12906030_124355855000_2.png"
            , "http://f.hiphotos.baidu.com/image/h%3D200/sign=19301b3790dda144c5096bb282b6d009/574e9258d109b3de89655b4ccbbf6c81800a4c3f.jpg"
            , "http://img2.duitang.com/uploads/item/201204/22/20120422200645_TUrrj.thumb.600_0.jpeg"
            , "http://photo.l99.com/bigger/22/1363590002923_qwy54a.jpg"};

    private RecommendPresenter presenter;
    private DocPresenter docPresenter;
    private AdPresenter adPresenter;
    private ReportPresenter reportPresenter;
    private RecommendAdapter mAdapter1;
    private RecommendAdapter mAdapter2;
    private RecommendAdapter mAdapter3;
    private RecommendReportAdapter mAdapter4;
    private InfoAdapter mAdapter5;

    public static SwipeRefreshLayout mSwipe;
    private int refreshNum = 0;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    public String province = "";
    private List<AdBean> adInfo = new ArrayList<>();

    private View view;
    //    private BannerView mViewPager;
    private Kanner kannerView;

    @Override
    public void onItemClick(int position, RecomHotInfo info) {
        if (info == null) {
            return;
        }
        if (info.getURL() != null) {
            L.d("主页点击2" + info.getURL());
            L.d(info.getURL());
            DetailActivity.startActivity(getActivity(), info.getNAME(), info.getID(), "conference", info.getURL());
        }
    }

    @Override
    public void adResult(final AdInfo infos) {
        if (infos != null) {
            String[] res = new String[infos.getContents().size()];
            L.d("轮播图" + infos.getContents().size());
            for (int i = 0; i < infos.getContents().size(); i++) {
                res[i] = infos.getContents().get(i).getThumb_pad();
                L.d("轮播图" + res[i]);
            }
            kannerView.setImagesUrl(res);

            kannerView.setOnKannerListener(new Kanner.OnKannerListener() {
                @Override
                public void setOnKannerListener(int pos) {
//                    pos=pos % (infos.getContents().size() - 1) + 1;[222-1],[033-2],[114-0]
//                    T.showShort(getContext(), pos);
                    if (pos == 2) {
                        pos = 1;
                    } else if (pos == 0 || pos == 3) {
                        pos = 2;
                    } else if (pos == 1 || pos == 4) {
                        pos = 0;
                    }

                    DetailActivity.startActivity(getActivity(), infos.getContents().get(pos).getTitle(), String.valueOf(infos.getContents().get(pos).getId()), "", infos.getContents().get(pos).getHref_url());
                }
            });

//            adInfo.addAll(infos.getContents());
//            for (final AdBean info : infos.getContents()) {
//                mViewPager.addItem("", info.getThumb_pad(), new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        DetailActivity.startActivity(getActivity(),info.getTitle(),String.valueOf(info.getId()), "", info.getHref_url());
//                    }
//                });
//            }
        }
    }

    //报道
    @Override
    public void onItemClick(int position, ReportInfoItem info) {
        L.d("链接报道" + info.getType() + info.getUrl());
//        T.showShort(getContext(),"报道");
        DetailActivity.startActivity(getActivity(), info.getTitle(), info.getId(), info.getType(), info.getUrl());
    }


    private class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            province = location.getProvince();
            presenter.getLocalResult("1", "4", province);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLocationClient = new LocationClient(MyApplication.getInstance());     //声明LocationClient类
        initLocation();
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        mLocationClient.start();
    }


    public static RecommendFragment newInstance() {
        RecommendFragment fragment = new RecommendFragment();
        return fragment;
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view != null) {

            return view;
        }

        view = inflater.inflate(R.layout.fragment_recommend, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        kannerView = (Kanner) view.findViewById(R.id.viewpager);
//        ViewPager.LayoutParams la=new ViewPager.LayoutParams());
        kannerView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ScreenUtils.getScreenHeight(getActivity()) / 3));


        mRecyclerItem1 = (RecyclerView) view.findViewById(R.id.rv_home_item1);
        mRecyclerItem2 = (RecyclerView) view.findViewById(R.id.rv_home_item2);
        mRecyclerItem3 = (RecyclerView) view.findViewById(R.id.rv_home_item3);
        mRecyclerItem4 = (RecyclerView) view.findViewById(R.id.rv_home_item4);
        mRecyclerItem5 = (RecyclerView) view.findViewById(R.id.rv_home_item5);
        mSwipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);

        mSwipe.setOnRefreshListener(this);
//        mSwipe.setEnabled(false);
        view.findViewById(R.id.tv_home_item1).setOnClickListener(this);
        view.findViewById(R.id.tv_home_item2).setOnClickListener(this);
        view.findViewById(R.id.tv_home_item3).setOnClickListener(this);
        view.findViewById(R.id.tv_home_item4).setOnClickListener(this);
        view.findViewById(R.id.tv_home_item5).setOnClickListener(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initRecyclerView();
        presenter = new RecommendPresenter(this);
        docPresenter = new DocPresenter(this);
        adPresenter = new AdPresenter(this);
        reportPresenter = new ReportPresenter(this);

        mSwipe.post(new Runnable() {
            @Override
            public void run() {
                mSwipe.setRefreshing(true);
                refreshNum = 0;
                presenter.getPhysicianResult("1", "4");
                presenter.getRecomHotData("1", "4");
                docPresenter.getDocData("1", "4", "");
                adPresenter.getAd();
                reportPresenter.getReport("1", "4", "3", "");
            }
        });
    }

    private void initRecyclerView() {
        mRecyclerItem1.setLayoutManager(new FullyGridLayoutManager(getContext(), 4));
        mRecyclerItem2.setLayoutManager(new FullyGridLayoutManager(getContext(), 4));
        mRecyclerItem3.setLayoutManager(new FullyGridLayoutManager(getContext(), 4));
        mRecyclerItem4.setLayoutManager(new FullyGridLayoutManager(getContext(), 2));
        mRecyclerItem5.setLayoutManager(new FullyGridLayoutManager(getContext(), 2));
        mRecyclerItem1.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.HORIZONTAL_LIST));
        mRecyclerItem2.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.HORIZONTAL_LIST));
        mRecyclerItem3.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.HORIZONTAL_LIST));
        mRecyclerItem4.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.HORIZONTAL_LIST));
        mRecyclerItem5.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.HORIZONTAL_LIST));
        mAdapter1 = new RecommendAdapter(getActivity());
        mAdapter2 = new RecommendAdapter(getActivity());
        mAdapter3 = new RecommendAdapter(getActivity());
        mAdapter4 = new RecommendReportAdapter("home");
        mAdapter1.setOnItemClickListener(this);
        mAdapter2.setOnItemClickListener(this);
        mAdapter3.setOnItemClickListener(this);
        mAdapter4.setOnItemClickListener(this);
        mAdapter5 = new InfoAdapter("home");
        mAdapter5.setOnItemClickListener(new InfoAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, DocInfoItem data) {
                L.d("主页点击1" + data.getURL());
                DetailActivity.startActivity(getActivity(), data.getTITLE(), data.getID(), data.getTYPE(), data.getURL());
            }
        });
        mRecyclerItem1.setAdapter(mAdapter1);
        mRecyclerItem2.setAdapter(mAdapter2);
        mRecyclerItem3.setAdapter(mAdapter3);
        mRecyclerItem4.setAdapter(mAdapter4);
        mRecyclerItem5.setAdapter(mAdapter5);
    }

    @Override
    public void onResume() {
        super.onResume();
//        mViewPager.startTurning(3000);
    }

    @Override
    public void onDestroyView() {
//        mViewPager.stopTurning();
        super.onDestroyView();
    }

    @Override
    public void onRefresh() {
        refreshNum = 0;
        adPresenter.getAd();
        presenter.getPhysicianResult("1", "4");
        presenter.getRecomHotData("1", "4");
        presenter.getLocalResult("1", "4", province);
        docPresenter.getDocData("1", "4", "");
        reportPresenter.getReport("1", "4", "3", "");
    }

    @Override
    public void setRPhysicianResult(Msg msg, DataInfo data) {
        ++refreshNum;
        isRefreshing(false);
        mAdapter1.clear();
        if (data != null) {
            mAdapter1.addAll(data.getPAGE().getList());
        }
    }

    @Override
    public void setLPhysicianResult(Msg msg, DataInfo data) {

    }

    @Override
    public void setPhysicianError(Call call, Exception e) {
        isRefreshing(true);
    }

    @Override
    public void setRLocalResult(Msg msg, DataInfo data) {
        ++refreshNum;
        isRefreshing(false);
        mAdapter2.clear();
        if (data != null) {
            mAdapter2.addAll(data.getPAGE().getList());
        }
    }

    @Override
    public void setLLocalResult(Msg msg, DataInfo data) {

    }

    @Override
    public void setLocalError(Call call, Exception e) {
        isRefreshing(true);
    }

    @Override
    public void setRHotResult(Msg msg, DataInfo data) {
        ++refreshNum;
        isRefreshing(false);
        mAdapter3.clear();
        if (data != null) {
            mAdapter3.addAll(data.getPAGE().getList());
        }
    }

    @Override
    public void setLHotResult(Msg msg, DataInfo data) {

    }

    @Override
    public void setHotError(Call call, Exception e) {
        isRefreshing(true);
    }

    @Override
    public void setRReportResult(Msg msg, DataReportInfo data) {
        ++refreshNum;
        isRefreshing(false);
        mAdapter4.clear();
        if (data != null) {
            mAdapter4.addAll(data.getList());
        }
    }

    @Override
    public void setLReportResult(Msg msg, DataReportInfo data) {

    }

    @Override
    public void setReportError(Call call, Exception e) {
        isRefreshing(true);
    }


    @Override
    public void setPageRefreshResult(Msg msg, DataDocInfo data) {
        ++refreshNum;
        isRefreshing(false);
        mAdapter5.clear();
        if (data != null) {
            mAdapter5.addAll(data.getPAGE().getList());
        }
    }

    @Override
    public void setPageLoadResult(Msg msg, DataDocInfo data) {

    }

    @Override
    public void setPageError(Call call, Exception e) {
        isRefreshing(true);
    }

    public void isRefreshing(boolean b) {
        if (b) {
            mSwipe.setRefreshing(false);
            return;
        }
        if (mSwipe.isRefreshing() && refreshNum == 4) {
            mSwipe.setRefreshing(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_home_item1:
                ConferenceListActivity.startActivity(getActivity(), "physicians", province);
                break;
            case R.id.tv_home_item2:
                EventBus.getDefault().post(new GetMessage("checkMeeting"));
                if (province == null) {
                    province = "";
                }
                EventBus.getDefault().post(new MainEvent("", province));//null坐不了巴士
//                ConferenceListActivity.startActivity(getActivity(), "local", province);
                break;
            case R.id.tv_home_item3:
                EventBus.getDefault().post(new GetMessage("checkMeeting"));
                EventBus.getDefault().post(new MainEvent("hot", ""));
//                ConferenceListActivity.startActivity(getActivity(), "hot", province);
                break;
            case R.id.tv_home_item4:
//                ConferenceListActivity.startActivity(getActivity(), "report", province);
                Intent toSearch = new Intent();
                toSearch.setClass(getActivity(), SearchActivity.class);
                toSearch.putExtra("toNews", "toNews");
                startActivity(toSearch);
                break;
            case R.id.tv_home_item5:
                EventBus.getDefault().post(new GetMessage("toDoc"));
//                ConferenceListActivity.startActivity(getActivity(), "info", province);
                break;
        }
    }

    @Override
    public String getPageName() {
        return "RecommendFragment";
    }
}
